app.factory("HashList", ["$rootScope", function ($rootScope) {

    function HashListProvider(options) {
        this.groupBy = options.groupBy;
        //console.log(this.__proto__.constructor.name, "groupBy", options.groupBy);
    };

    HashListProvider.prototype = new Array();
    HashListProvider.prototype.constructor = HashListProvider;

    HashListProvider.prototype.insert = function (item) {

        //console.log("prop1 on", item, "groupBy", this.groupBy);
        var prop = $rootScope.$eval(this.groupBy, item);
        //console.log("prop2:", prop);
        var v = this.get(prop);
        //console.log(this.__proto__.constructor.name, "insert[",v.key,"]:",item);
        v.values.push(item);
    };

    HashListProvider.prototype.get = function (key) {
        var self = this;
        var selection = null;
        self.forEach(function (item) {

            //console.log("compare", key, " to ", item.key);

            if (item.key == key) {
                selection = item;
                return;
            };
        });

        if (selection) return selection;

        var newItem = { key: key, values: [] };
        self.push(newItem);
        return newItem;
    }


    HashListProvider.prototype.insertList = function (list) {
        var self = this;
        list.forEach(function (item) {
            self.insert(item)
        });
    };

    HashListProvider.prototype.clear = function () {
        this.splice(0, this.length);
        console.log(this.__proto__.constructor.name, "clear. length", this.length);
    };

    HashListProvider.prototype.remove = function (item) {
        var self = this;
        self.forEach(function (i) {

            var index = i.values.indexOf(item);
            if (index >= 0) i.splice(index, 1);
        });
    };

    HashListProvider.prototype.flatten = function () {
        var list = [];
        list.forEach(function (i) {
            list = list.concat(i.values);
        });
        return list;
    };

    return HashListProvider;
} ]);